' ----------------------------------------------------
' function: LeadZero
' Padding zero to a number
' ----------------------------------------------------
function LeadZero(n, width)
	dim s : s = CStr(n)
	if len(s) < width then
		LeadZero = String(width - len(s), "0") + s
		exit function
	end if
	LeadZero = s
end function

' ----------------------------------------------------
' function: MonthShortForm
' returns the short form of a month, e.g. Jan
' ----------------------------------------------------
function MonthShortForm(m)
	dim names : names = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
	MonthShortForm = names(m - 1)
end function

function FormatDate(d, fmtstr)
	dim v : v = CDate(d)
	dim ret
	ret = replace(fmtstr, "YYYY", LeadZero(Year(v) mod 10000, 4))
	ret = replace(ret, "yyyy", LeadZero(Year(v) mod 10000, 4))
	ret = replace(ret, "YY", LeadZero(Year(v) mod 100, 2))
	ret = replace(ret, "yy", LeadZero(Year(v) mod 100, 2))
	ret = replace(ret, "MMM", UCase(MonthShortForm(Month(v))))
	ret = replace(ret, "Mmm", MonthShortForm(Month(v)))
	ret = replace(ret, "mmm", LCase(MonthShortForm(Month(v))))
	ret = replace(ret, "mm", LeadZero(Month(v), 2))
	ret = replace(ret, "DD", LeadZero(Day(v), 2))
	ret = replace(ret, "dd", LeadZero(Day(v), 2))
	FormatDate = ret
end function

function FormatTime(t, fmtstr)
	dim v : v = CDate(t)
	dim ret
	ret = replace(fmtstr, "HH", LeadZero(Hour(v) mod 100, 2))
	ret = replace(ret, "hh", LeadZero(Hour(v) mod 100, 2))
	ret = replace(ret, "MM", LeadZero(Minute(v), 2))
	ret = replace(ret, "SS", LeadZero(Second(v), 2))
	ret = replace(ret, "ss", LeadZero(Second(v), 2))
	FormatTime = ret
end function

sub Main()
	dim v : v = Now
	dim fmt, str

	fmt = "YYYY-mm-DD_HHMMSS"
	if wsh.Arguments.Count > 0 then
		fmt = wsh.Arguments(0)
		if fmt = "--help" then
			wsh.echo "datetime - Generate current date time in format"
			wsh.echo "usage: datetime [FORMAT]"
			exit sub
		end if
	end if

	str = FormatDate(v, fmt)
	str = FormatTime(v, str)
	wsh.echo str
end sub

call Main